package com.bootdo.common.task;

import com.bootdo.lgs.lgsInterfaces.jzy.JzyLogisticsService;
import com.bootdo.lgs.lgsInterfaces.jzy.dto.TraceData;
import com.bootdo.lgs.lgsInterfaces.jzy.service.JzyService;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.ordertrace.model.LgsOrderStatusUpdate;
import com.bootdo.lgs.ordertrace.service.OrderTraceService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class LgsTrackJzyJob implements Job{

    private static final Logger logger = LoggerFactory.getLogger(LgsTrackJzyJob.class);

    @Autowired
    private JzyService jzyService;

    @Autowired
    private OrderTraceService orderTraceService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("更新 今朝阳 跟踪信息 开始："+System.currentTimeMillis());
        logger.info("开始刷新登陆信息");
        JzyLogisticsService.refreshLoginInfo();//先刷新登陆信息
        // 先查询出来目前已发货（状态5）还未签收的订单（今朝阳）
        List<LgsOrder> lgsOrders = jzyService.getUnCheckOrderTrace();
        // 如果未签收订单为空 结束任务
        if(lgsOrders==null||lgsOrders.isEmpty())
            return;
        // 循环 对这些订单 发起请求获取物流跟踪信息
        List<LgsOrderStatusUpdate> lgsOrderStatusUpdateList = new ArrayList<>();//批量更新物流状态
        List<Long> orderIds = new ArrayList<>(); //批量删除订单跟踪信息 的订单id
        List<Map> orderTraceList = new ArrayList<>();//查询到的最新的跟踪信息
        System.out.println("准备更新物流信息：");
        List<String> traceNumbers = lgsOrders.stream().map(LgsOrder::getLgs_track_number).collect(Collectors.toList());//构建物流单号list
        //（今朝阳接口限制：一次最多查询50个单号）每45个查询一次
        Map<String, List<TraceData>> jzyMap = new ConcurrentHashMap<>();
        if(traceNumbers.size()<=45) {
            jzyMap = getTraceDataMap(traceNumbers);
        }else{
            List<String> list = new ArrayList<>();
            for(String sr : traceNumbers){
                list.add(sr);
                if(list.size()==45){
                    jzyMap.putAll( getTraceDataMap(list) );
                    list.clear();
                }
            }
            if(list.size()>0)
                jzyMap.putAll( getTraceDataMap(list) );
        }
        //遍历map、获取的订单有跟踪信息时才 记录到 orderIds，orderTraceList
        Iterator map = jzyMap.keySet().iterator();

        while(map.hasNext()) {
            String key = (String)map.next(); //key 就是物流运单号
            LgsOrder lgsOrder = lgsOrders.stream().filter(item->item.getLgs_track_number().equals(key)).findFirst().get(); //根据物流运单号找到 lgsOrder
            List<TraceData> tdList = (List)jzyMap.get(key);
            if(tdList==null||tdList.isEmpty())
                continue;
            orderIds.add(lgsOrder.getId());
            //List<TraceData> sortList = tdList.stream().sorted(Comparator.comparing(TraceData::getTraceTime)).collect(Collectors.toList()); //根据时间排序
            // 如果签收状态为已签收、更新订单为已签收状态7
            if(ischeck(tdList)){
                LgsOrderStatusUpdate lgsOrderStatusUpdate = new LgsOrderStatusUpdate();
                lgsOrderStatusUpdate.setLgs_status("7");
                lgsOrderStatusUpdate.setId(lgsOrder.getId());
                lgsOrderStatusUpdateList.add(lgsOrderStatusUpdate);
            }
            //逆序循环,
            for(int i=tdList.size()-1;i>=0;i--){
                Map<Object, Object> lgsMap = new ConcurrentHashMap<>();
                lgsMap.put("ftime", tdList.get(i).getTraceTime().replace("T"," "));
                lgsMap.put("context", tdList.get(i).getStatusComment());
                lgsMap.put("orderId", lgsOrder.getId());
               // lgsMap.put("ischeck", ischeck);
                orderTraceList.add(lgsMap);
            }
        }
        // 封装数据到对象、更新订单的物流跟踪信息
        orderTraceService.batchRefreshOrderTrace(lgsOrderStatusUpdateList,orderIds,orderTraceList);//更新物流跟踪信息
        System.out.println("更新 今朝阳 跟踪信息 结束："+System.currentTimeMillis());
    }

    private Map<String, List<TraceData>> getTraceDataMap(List<String> traceNumbers){
        try {
            return JzyLogisticsService.batchQueryTraceData(JzyLogisticsService.login(), traceNumbers);
        } catch (Exception e) {
            logger.warn("获取【今朝阳】接口失败",e);
        }
        return new ConcurrentHashMap<>();
    }

    /** 返回1 表示签收、0 未签收 */
    private boolean ischeck(List<TraceData> tdList){
        for (TraceData traceData:tdList) {
//            if(traceData.getStatus()!=null&& traceData.getStatus().contains("已签收") )
//                return true;

            if(traceData.getStatus()!=null){
                String status = traceData.getStatus().trim();
                if(status.contains("已签收") || status.contains("确认签收"))
                        return true;
            }
        }
        return false;
    }

}
